package com.ruoyi.web.controller.work;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.work.domain.WorkInvoice;
import com.ruoyi.work.domain.WorkPaper;
import com.ruoyi.work.service.IWorkInvoiceService;
import com.ruoyi.work.service.IWorkPaperService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.work.domain.WorkIncoming;
import com.ruoyi.work.service.IWorkIncomingService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 收款认领Controller
 *
 * @author ruoyi
 * @date 2021-12-21
 */
@Controller
@RequestMapping({"/work/incoming", "/work/reg","/work/belong"})
public class WorkIncomingController extends BaseController {
    private String prefix = "work/incoming";

    @Autowired
    private IWorkIncomingService workIncomingService;
    @Autowired
    private IWorkInvoiceService workInvoiceService;
    @Autowired
    private IWorkPaperService workPaperService;

    @RequiresPermissions("work:incoming:view")
    @GetMapping()
    public String incoming() {
        return prefix + "/incoming";
    }


    /**
     * 查询销账列表
     */
    @RequiresPermissions("work:incoming:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkIncoming workIncoming) {
        startPage();
        //todo
        workIncoming.setBelong(getUserName());
        List<WorkIncoming> list = workIncomingService.selectWorkIncomingList(workIncoming);
        return getDataTable(list);
    }
    /**
     * 来款登记
     */
    @RequiresPermissions("work:incoming:reglist")
    @PostMapping("/reglist")
    @ResponseBody
    public TableDataInfo reglist(WorkIncoming workIncoming) {
        startPage();
        List<WorkIncoming> list = workIncomingService.selectWorkIncomingList(workIncoming);
        return getDataTable(list);
    }

    /**
     * 导出收款认领列表
     */
    @RequiresPermissions("work:incoming:export")
    @Log(title = "收款认领", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkIncoming workIncoming) {
        List<WorkIncoming> list = workIncomingService.selectWorkIncomingList(workIncoming);
        ExcelUtil<WorkIncoming> util = new ExcelUtil<WorkIncoming>(WorkIncoming.class);
        return util.exportExcel(list, "收款认领数据");
    }

    /**
     * 新增收款认领
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存收款认领
     */
    @RequiresPermissions("work:incoming:add")
    @Log(title = "来款登记", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WorkIncoming workIncoming) {
        workIncoming.setCreateBy(getLoginName());
        return toAjax(workIncomingService.insertWorkIncoming(workIncoming));
    }

    /**
     * 修改来款登记
     */
    @RequiresPermissions("work:incoming:edit")
    @GetMapping("/edit/{incomingId}")
    public String edit(@PathVariable("incomingId") Long incomingId, ModelMap mmap) {
        WorkIncoming workIncoming = workIncomingService.selectWorkIncomingByIncomingId(incomingId);
        mmap.put("workIncoming", workIncoming);
        return prefix + "/edit";
    }

    /**
     * 修改保存来款登记
     */
    @RequiresPermissions("work:incoming:edit")
    @Log(title = "来款登记", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkIncoming workIncoming) {
        return toAjax(workIncomingService.updateWorkIncoming(workIncoming));
    }

    /**
     * 删除来款登记
     */
    @RequiresPermissions("work:incoming:remove")
    @Log(title = "收款认领", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(workIncomingService.deleteWorkIncomingByIncomingIds(ids));
    }

    /**
     * 来款认领与注销
     *
     * @param incomingId
     * @param status
     * @param mmap
     * @return
     */
    @RequiresPermissions("work:incoming:belong")
    @PostMapping("/belong/{incomingId}")
    @ResponseBody
    public AjaxResult belong(@PathVariable("incomingId") Long incomingId, String status, ModelMap mmap) {
        WorkIncoming workIncoming = workIncomingService.selectWorkIncomingByIncomingId(incomingId);
        if (status.equals("0")) {
            if (StringUtils.isNotEmpty(workIncoming.getBelong())) {
                return AjaxResult.error("该来款记录已经被认领！");
            }
            workIncoming.setBelong(getUserName());
            workIncoming.setBelongTime(DateUtils.getNowDate());
        } else if (status.equals("1")) {
            if (StringUtils.isEmpty(workIncoming.getBelong())) {
                return AjaxResult.error("不能注销未认领的来款记录！");
            }
            if (workIncoming.getBelong() != null && !workIncoming.getBelong().equals(getUserName())) {
                return AjaxResult.error("不能注销认领人非本人的来款记录！");
            }
            if (workIncoming.getExpenseLimit().compareTo(BigDecimal.ZERO) == 1) {
                return AjaxResult.error("不能注销已经开始销账的来款记录！");
            }
            workIncoming.setBelong(null);
            workIncoming.setBelongTime(null);
        }

        return toAjax(workIncomingService.updateWorkIncoming(workIncoming));
    }

    /**
     * 打开销账页面(有发票)
     */
    @RequiresPermissions("work:incoming:cancel")
    @GetMapping("/cancel/{incomingId}")
    public String cancel(@PathVariable("incomingId") Long incomingId, ModelMap mmap) {

        List<WorkInvoice> workInvoices = workInvoiceService.selectInvoiceByCancel(incomingId);
        if (workInvoices.size() == 1) {
            Map<String, Object> map = new HashMap<>();
            map.put("incomingId",incomingId);
            map.put("invoiceId",workInvoices.get(0).getInvoiceId());

            Long[] papers = workPaperService.selectPaperByCancel(map).stream().map(WorkPaper::getPaperId).toArray(Long[]::new);

            mmap.put("papers", StringUtils.join(papers, ','));
        }
        mmap.put("incomingId", incomingId);


        return prefix + "/cancel";
    }

    /**
     * 打开销账页面（无发票）
     */
    @RequiresPermissions("work:incoming:off")
    @GetMapping("/off/{incomingId}")
    public String off(@PathVariable("incomingId") Long incomingId, ModelMap mmap) {

        Map<String, Object> map = new HashMap<>();
        map.put("incomingId",incomingId);
        map.put("invoiceId",0L);
        Long[] papers = workPaperService.selectPaperByCancel(map).stream().map(WorkPaper::getPaperId).toArray(Long[]::new);

        mmap.put("papers", StringUtils.join(papers, ','));

        mmap.put("incomingId", incomingId);


        return prefix + "/off";
    }

    /**
     * 销账页面单条销账记录
     */
    /* @RequiresPermissions("work:incoming:cancellist")*/
    @PostMapping("/cancellist/{incomingId}")
    @ResponseBody
    public TableDataInfo cancellist(@PathVariable("incomingId") Long incomingId) {

        List<WorkIncoming> list = new ArrayList<>();
        WorkIncoming workIncoming = workIncomingService.selectWorkIncomingByIncomingId(incomingId);
        list.add(workIncoming);
        return getDataTable(list);
    }

    /**
     * 销账选择弹窗报销单页面
     */
    /*@RequiresPermissions("work:incoming:expense")*/
    @GetMapping("/expense/{exType}")
    public String expense(@PathVariable("exType") Long exType, ModelMap mmap) {
        mmap.put("exType", exType);
        return prefix + "/expense";
    }

    /**
     * 销账选择弹窗发票页面
     */
    /*@RequiresPermissions("work:incoming:invoice")*/
    @GetMapping("/invoice")
    public String invoice(ModelMap mmap) {
        return prefix + "/invoice";
    }

    /**
     * 销账选择弹窗发票页面
     */
    /* @RequiresPermissions("work:incoming:paper")*/
    @GetMapping("/paper/{incomingId}/{invoiceId}")
    public String paper(@PathVariable("incomingId") Long incomingId, @PathVariable("invoiceId") Long invoiceId, ModelMap mmap) {
        mmap.put("invoiceId", invoiceId);
        mmap.put("incomingId", incomingId);
        return prefix + "/paper";
    }


    /**
     * 新增保存销账税金、返款单、发票、部分稿件
     */
    /*@RequiresPermissions("work:incoming:addcancel")*/
    @PostMapping("/addcancel/{cacelType}")
    @ResponseBody
    public AjaxResult addCancel(@PathVariable("cacelType") String cacelType, WorkIncoming workIncoming) {
        workIncoming.setCancelType(cacelType);
        return toAjax(workIncomingService.insertCancel(workIncoming));
    }

    /**
     * 审核销账信息
     */
    @RequiresPermissions("work:incoming:check")
    @Log(title = "审核销账", businessType = BusinessType.CHECK)
    @PostMapping("/check")
    @ResponseBody
    public AjaxResult check(String[] ids) {
        try {

            List<WorkIncoming> list = workIncomingService.selectWorkIncomingByIncomingIds(ids);
            if (list.stream().anyMatch(w -> !w.getCheckStatus().equals("1"))) {
                return AjaxResult.error("必须为未审核状态");
            }
            list.forEach(e -> {

                e.setCheckStatus("2");
                workIncomingService.updateWorkIncoming(e);
            });
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 提成
     */
    @RequiresPermissions("work:incoming:grant")
    @Log(title = "提成", businessType = BusinessType.GRANT)
    @PostMapping("/grant")
    @ResponseBody
    public AjaxResult grant(String[] ids) {
        try {
            List<WorkIncoming> list = workIncomingService.selectWorkIncomingByIncomingIds(ids);
            if (list.stream().anyMatch(w -> !w.getCheckStatus().equals("2"))) {
                return AjaxResult.error("必须为已审核状态");
            }
            list.forEach(e -> {

                //TODO 设置稿件提成时间与提成
                //TODO 设置销账状态已提成
                //总报价-总低价=利润 （无发票）
                //总报价-总低价-税点=利润（有发票）
                //利润乘以0.2
                //todo 查看功能
                e.setCheckStatus("3");
                workIncomingService.updateWorkCommission(e.getIncomingId());
                workIncomingService.updateWorkIncoming(e);
            });
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }
}
